<template>
    <el-form
        :inline="true"
        ref="searchFormRef"
        style="max-width: 100%"
        label-width="auto"
        :model="queryConditions"
        class="demo-ruleForm"
        status-icon
    >
        <el-form-item label="仓库" prop="storeId">
            <el-select
                v-model="queryConditions.storeId"
                style="width: 200px"
                size="large"
                placeholder="请选择"
                clearable
            >
                <el-option
                    v-for="store in storeList"
                    :key="store.id"
                    :label="store.name"
                    :value="store.id"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="商品编码" prop="goodsCode">
            <el-input
                v-model="queryConditions.goodsCode"
                style="width: 200px"
                size="large"
                placeholder="请输入商品编码"
                clearable
            />
        </el-form-item>
        <el-button type="primary" :icon="Search" @click="search">查询</el-button>
        <el-button type="primary" :icon="RefreshRight" @click="resetForm">重置</el-button>
    </el-form>
    <el-table :data="formattedTableData" border style="width: 100%">
        <el-table-column prop="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="goodsCode" label="商品编码" width="150"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称" width="150"></el-table-column>
        <el-table-column prop="docType" label="单据类型" width="120"></el-table-column>
        <el-table-column prop="docNo" label="单据编号" width="150"></el-table-column>
        <el-table-column prop="docDate" label="单据日期" width="150">
            <template #default="scope">
                {{ scope.row.docDate ? new Date(scope.row.docDate).toLocaleDateString('zh-cn') : '无' }}
            </template>
        </el-table-column>
        <el-table-column prop="storeName" label="仓库名称" width="150"></el-table-column>
        <el-table-column prop="unitName" label="单位" width="100"></el-table-column>
        <el-table-column label="入库" width="300">
            <el-table-column prop="inQuantity" label="数量" width="150"></el-table-column>
            <el-table-column prop="inPrice" label="单位成本" width="150"></el-table-column>
        </el-table-column>
        <el-table-column label="出库" width="300">
            <el-table-column prop="outQuantity" label="数量" width="150"></el-table-column>
            <el-table-column prop="outPrice" label="单位成本" width="150"></el-table-column>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总额" width="150"></el-table-column>
    </el-table>
    <el-pagination
        class="pagination-wrapper"
        background
        layout="prev, pager, next"
        :total="allPage"
        :page-size="pageSize"
        :current-page="pageNo"
        @current-change="handlePageChange"
    />
</template>

<script setup lang="ts">
import {onMounted} from 'vue';
import {Search, RefreshRight} from '@element-plus/icons-vue';
import {ref, computed, reactive, nextTick} from 'vue';
import {ElMessage, type FormInstance} from 'element-plus';
import axios from 'axios';

let pageNo = ref(1);
let pageSize = ref(10);
let allPage = ref(0);
const searchFormRef = ref<FormInstance>();

// 查询条件
const queryConditions = reactive({
    storeId: null,
    goodsCode: ''
});

// 查询
const search = () => {
    pageNo.value = 1;
    fetchData(1);
};

// 重置表单
const resetForm = () => {
    if (!searchFormRef.value) return;
    nextTick(() => {
        searchFormRef.value!.resetFields();
        queryConditions.storeId = null;
        pageNo.value = 1;
        fetchData(1);
    });
};

let tableData = ref<any[]>([]);

// 格式化表格数据
const formattedTableData = computed(() => {
    const result = tableData.value.map((item, index) => {
        // 判断单据类型
        let docType = '无';
        if (item.purchaseInDocNo) {
            docType = '采购入库';
        } else if (item.saleOutDocNo) {
            docType = '销售出库';
        } else if (item.otherOutDocNo) {
            docType = '其他出库';
        } else if (item.inventoryGainDocNo) {
            docType = '盘盈';
        } else if (item.inventoryLossDocNo) {
            docType = '盘亏';
        }

        const docNo = item.purchaseInDocNo || item.saleOutDocNo || item.otherOutDocNo || item.inventoryGainDocNo || item.inventoryLossDocNo || '无';
        const docDate = item.purchaseInDocDate || item.saleOutDocDate || item.otherOutDocDate || item.inventoryGainDocDate || item.inventoryLossDocDate || null;

        const inQuantity = (item.purchaseInQuantity || 0) + (item.inventoryGainQuantity || 0);
        const outQuantity = (item.saleOutQuantity || 0) + (item.otherOutQuantity || 0) + (item.inventoryLossQuantity || 0);
        const inPrice = item.purchaseInPrice || item.inventoryGainPrice || 0;
        const outPrice = item.saleOutPrice || item.otherOutPrice || item.inventoryLossPrice || 0;
        const totalAmount = (inQuantity * inPrice) + (outQuantity * outPrice);

        return {
            index: (pageNo.value - 1) * pageSize.value + index + 1,
            goodsCode: item.goodsCode || '未知编码',
            goodsName: item.goodsName || '未知商品',
            storeName: item.storeName || '未知仓库',
            unitName: item.unitName || '无',
            docType: docType,
            docNo: docNo,
            docDate: docDate,
            inQuantity: Number(inQuantity).toFixed(2),
            inPrice: Number(inPrice).toFixed(2),
            outQuantity: Number(outQuantity).toFixed(2),
            outPrice: Number(outPrice).toFixed(2),
            totalAmount: Number(totalAmount).toFixed(2)
        };
    });
    return result;
});

// 分页处理
const handlePageChange = (newPage: number) => {
    pageNo.value = newPage;
    fetchData(newPage);
};

// 获取数据
async function fetchData(page: number) {
    try {
        const response = await axios.post('http://localhost:8089/StoreGoodSummary/selectSummaryByGoodsTransactionDetail', {
            pageNo: page,
            pageSize: pageSize.value,
            storeId: queryConditions.storeId,
            goodsCode: queryConditions.goodsCode
        });
        tableData.value = response.data.data.list;
        allPage.value = response.data.data.total;
    } catch (error) {
        ElMessage.error('获取交易明细数据失败');
        tableData.value = [];
        allPage.value = 0;
    }
}

// 获取仓库列表
const storeList = ref<any[]>([]);
const fetchAllStores = async () => {
    try {
        const res = await axios.post('http://localhost:8089/StoreGoodSummary/selectAll');
        storeList.value = res.data.data;
    } catch (e) {
        ElMessage.error('获取仓库数据失败');
        storeList.value = [];
    }
};

onMounted(() => {
    fetchData(1);
    fetchAllStores();
});
</script>

<style scoped>
.customer-table-container {
    background: #fff;
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-actions {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
}

.left-actions {
    display: flex;
    gap: 8px;
}

.pagination-wrapper {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}

.el-tag {
    padding: 0 8px;
    height: 24px;
    line-height: 24px;
}
</style>
